/**
 * 用户管理模块
 */
const router = require("koa-router")();
const User = require("./../models/userSchema");
const R = require("./../utils/R");
router.prefix("/users");

// 用户登录
router.post("/login", async (ctx) => {
  try {
    const { userName, userPwd } = ctx.request.body;
    /**
     * 返回数据库指定字段，有三种方式
     * 1. 'userId userName userEmail state role deptId roleList'
     * 2. {userId:1,_id:0}
     * 3. select('userId')
     */
    const res = await User.findOne(
      {
        userName,
        userPwd,
      },
      "userId userName userEmail state role deptId roleList"
    );

    if (res) {
      const data = res
      ctx.body = R.success(data);
    } else {
      ctx.body = R.fail("账号或密码不正确");
    }
  } catch (error) {
    ctx.body = R.fail(error.msg);
  }
});

// 用户注册
router.post("/register", async (ctx) => {
  try {
    const { userName, userPwd } = ctx.request.body;
    const res = await User.find({userName}).count();

    if (res > 0) {
      ctx.body = R.fail("账号已存在");
    } else {
      const user = await User.create({userName, userPwd});
      ctx.body = R.success(user);
    }
  } catch (error) {
    ctx.body = R.fail(error.msg);
  }
})
module.exports = router;
